package com.yb.web.tribune;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import com.opensymphony.xwork2.ActionContext;
import com.yb.base.web.BaseAction;
import com.yb.bussiness.announcement.AnnouncementService;
import com.yb.bussiness.announcement.AnnouncementServiceImpl;
import com.yb.bussiness.shoper.BrandService;
import com.yb.bussiness.shoper.BrandServiceImpl;
import com.yb.bussiness.tribune.TribuneFlowService;
import com.yb.bussiness.tribune.TribuneFlowServiceImpl;
import com.yb.bussiness.tribune.TribuneMasterService;
import com.yb.bussiness.tribune.TribuneMasterServiceImpl;
import com.yb.bussiness.tribune.TribunePresentedService;
import com.yb.bussiness.tribune.TribunePresentedServiceImpl;
import com.yb.bussiness.tribune.TribuneService;
import com.yb.bussiness.tribune.TribuneServiceImpl;
import com.yb.domain.goods.TgAnnouncement;
import com.yb.domain.goods.TgBrand;
import com.yb.domain.member.TsSysuser;
import com.yb.domain.tribune.Tribune;
import com.yb.domain.tribune.TribuneFlow;
import com.yb.domain.tribune.TribuneMaster;
import com.yb.domain.tribune.TribunePresented;
import com.yb.util.comm.Contants;
import com.yb.util.comm.RequestUtil;
import com.yb.util.framework.PageUtil;

/**
 * TribuneAction entity.
 * 
 * @author MyEclipse Persistence Tools
 */

public class TribuneAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private List<Tribune> triList;
	private List<TribuneFlow> triFlowList;
	private Tribune triObj;
	private TribuneFlow trif;
	private TgAnnouncement tgAnnouncement;
	
	private TribunePresented trip;
	private TribuneService service;
	private TribuneMasterService masterService;
	private TribuneFlowService flowService;
	private BrandService brandService;
	private TribunePresentedService tripService;
	private AnnouncementService annService;
	private String flag;
	private int total;
	private List<Tribune> rows;
	
	public TribuneAction() {
		service = new TribuneServiceImpl();
		flowService = new TribuneFlowServiceImpl();
		brandService = new BrandServiceImpl();
		tripService = new TribunePresentedServiceImpl();
		masterService = new TribuneMasterServiceImpl();
		annService = new AnnouncementServiceImpl();
	}

	/**
	 * 加载帖子
	 * @return
	 */
	public String loadTie(){
		String type = RequestUtil.getParam(request, "type", "0");
		try{
			int pageNo = RequestUtil.getParam(request, "pageNo", 1);
			int limit = RequestUtil.getParam(request, "limit", 30);
			PageUtil pu = service.loadTie(type, pageNo, limit);
			if(null!=pu.getList()&&pu.getList().size()>0)
					response.getWriter().print(JSONArray.fromObject(pu));
				else
					response.getWriter().print("[]");
		}catch(Exception e){
			log.error("查询论坛帖子集合出错", e);
			try {
				response.getWriter().print("[]");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 查看帖子
	 * @return
	 */
	public String searchById() {
		int pageno = RequestUtil.getParam(request, "pageno", 1);
		int limit = RequestUtil.getParam(request, "limit", 20);
		String id = RequestUtil.getParam(request, "id", "");
		triObj = service.getById(id);
		triObj.setLastVisitTime(new Date());
		try {
			triObj.setViewCount(triObj.getViewCount()+1);
		} catch (Exception e) {
			triObj.setViewCount(Long.valueOf(1));
		}
		service.saveOrUpdate(triObj);
		PageUtil pu = flowService.getListById(id,pageno, limit);
		ActionContext.getContext().put("pu", pu);
		return "viewPage";
	}
	
	/**
	 * 前台新增帖
	 * @return
	 */
	public String addtribune(){
		TsSysuser  tsSysuser = (TsSysuser) RequestUtil.getLoginUserFromSession(request, Contants.SESSION_USER);
		String flag = RequestUtil.getParam(request, "flag", "0");
		try {
			if(0!=triObj.getId())
				triObj.setCreateTime(service.read(triObj.getId()).getCreateTime());
			else{
				triObj.setCreateTime(new Date());
				triObj.setIsTop("0");
			}
			triObj.setAuthorId(tsSysuser.getId());
			triObj.setAuthorName(tsSysuser.getUsername());
			service.saveOrUpdate(triObj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if("1".equals(flag))
			return "successF";
		return "success";
	}
	/**
	 * 后台检索
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String search() {
		menuCls = RequestUtil.getParam(request, "menuCls", "");
		Map<String, String> map = new HashMap<String, String>();
		int page = RequestUtil.getParam(request, "page", 1);
		int row = RequestUtil.getParam(request, "rows", 10);
		String startTime = RequestUtil.getParam(request, "startTime", "");
		String endTime = RequestUtil.getParam(request, "endTime", "");
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		List<Tribune> list = service.getList(map, page, row);
		int count = service.getCount(map);
		if (list != null && list.size() > 0) {
			total = count;
			rows = list;
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}
	
	/**
	 * 后台新增帖
	 * @return
	 */
	public String addtribuneManage(){
		TsSysuser  tsSysuser = (TsSysuser) RequestUtil.getLoginUserFromSession(request, Contants.SESSION_USER);
		try {
			if(0!=triObj.getId()){
				Tribune obj = service.read(triObj.getId());
				obj.setTitle(triObj.getTitle());
				obj.setContent(triObj.getContent());
				service.saveOrUpdate(obj);
			}else{
				triObj.setCreateTime(new Date());
				triObj.setAuthorId(tsSysuser.getId());
				triObj.setAuthorName(tsSysuser.getUsername());
				triObj.setIsTop("0");
				service.saveOrUpdate(triObj);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "managesuccess";
	}
	
	
	
	/**
     * 送鲜花
     * 
     * @return
     */
    public String sendFlowerOrEgg() {
        try {
            TsSysuser tsSysuser = (TsSysuser)RequestUtil.getLoginUserFromSession(request, Contants.SESSION_USER);
            trip.setPresentedId(tsSysuser.getId());
            if (tripService.check(trip)) {
                response.getWriter().print("0");
            }
            else {
                long n = 0;
                triObj = service.read(trip.getTid());
                if (null != triObj) {
                    if (1 == trip.getFlag()) {
                        n = triObj.getFlowers() + 1l;
                        triObj.setFlowers(n);
                    }
                    else {
                        n = triObj.getEggs() + 1l;
                        triObj.setEggs(n);
                    }
                    service.saveOrUpdate(triObj);
                }
                else {
                    trif = flowService.read(trip.getTid());
                    if (1 == trip.getFlag()) {
                        n = trif.getFlowers() + 1l;
                        trif.setFlowers(n);
                    }
                    else {
                        n = trif.getEggs() + 1l;
                        trif.setEggs(n);
                    }
                    flowService.saveOrUpdate(trif);
                }
                tripService.saveOrUpdate(trip);
                response.getWriter().print("1");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            try {
                response.getWriter().print("2");
            }
            catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return null;
    }
	
	/**
	 * 送鸡蛋
	 * @return
	 */
	public String sendEgg(){
		try {
			triObj = service.read(new Long(trip.getTid()));
			if(null!=triObj){
				triObj.setEggs(triObj.getEggs()+1);
				service.saveOrUpdate(triObj);
				response.getWriter().print("1");
			}else
				response.getWriter().print("2");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
	
	public String julebuPage(){
		TsSysuser tsSysuser = (TsSysuser) RequestUtil.getLoginUserFromSession(request, Contants.SESSION_USER);
		ActionContext context = ActionContext.getContext();
		if(null!=tsSysuser){
			TribuneMaster obj = masterService.queryObjByUserId(tsSysuser.getId());
			if(null!=obj){
//				if (!DateTimeUtil.getDateToString(obj.getApplyTime(),"yyyy-MM-dd").equals(
//							DateTimeUtil.getDateToString(new Date(), "yyyy-MM-dd"))){
					context.put("tribuneMaster", obj.getAuding());
					if(!"1".equals(tsSysuser.getTribuneMaster())){
						tsSysuser.setTribuneMaster(obj.getAuding());
						RequestUtil.reSetLoginUser2Session(request,Contants.SESSION_USER,tsSysuser);
					}
//				}
			}
		}
		tgAnnouncement = annService.findTribuneByType("3"); 
		List<TgBrand> list = brandService.findAllBrand();
		Map<String,String> map=new HashMap<String,String>();
		map.put("userName","");
		map.put("auding","1");
		PageUtil tMlist = masterService.getList(map, 1, 10);
		if(null!=tMlist.getList())
			if(tMlist.getList().size()>0){
				String masterUserName = "";
				for (int i = 0; i < tMlist.getList().size(); i++) {
					masterUserName += ((TribuneMaster)tMlist.getList().get(i)).getUserName()+" ";
				}
				context.put("masterUserName", masterUserName);
			}
		context.put("tglist", list);
		return "julebuPage";
	}
	
	/**
	 * 论坛左侧品牌信息列表需要加上一页及下一页
	 * @return
	 */
	public String loadNextGroupPIC(){
		Map<String,String> parameMap = new HashMap<String,String>();
		try{
			String start = RequestUtil.getParam(request, "pageNo", "1");
			String limit = RequestUtil.getParam(request, "limit", "20");
			parameMap.put("start",start);
			parameMap.put("limit",limit);
			PageUtil pu = brandService.findAllShoperTOJulebu(parameMap);
			if(null!=pu.getList()&&pu.getList().size()>0)
					response.getWriter().print(JSONArray.fromObject(pu));
				else
					response.getWriter().print("[]");
		}catch(Exception e){
			log.error("论坛左侧品牌信息列表需要加上一页及下一页", e);
			try {
				response.getWriter().print("[]");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * 标记/撤销标记  为精华帖
	 * @return
	 */
	public String changeIsMarrow() {
		String id = RequestUtil.getParam(request, "id", "");
		String isMarrow = RequestUtil.getParam(request, "isMarrow", "");
		String idString = RequestUtil.getParam(request, "idString", "");

		boolean isFlag = false;
		if (!"".equals(id))
			isFlag = service.changeIsMarrowById(id,isMarrow);
		else
			isFlag = service.changeIsMarrowByIdString(idString,isMarrow);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		if (isFlag)
			message = "操作成功";
		else
			message = "操作失败";
		StringBuffer sb = new StringBuffer("[");
		sb.append("{\"message\":\"" + message + "\"" + "}");
		sb.append("]");

		try {
			out = response.getWriter();
			out.println(sb.toString());
		} catch (IOException e) {

			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 删帖
	 * @return
	 */
	public String deletetribune() {
		String id = RequestUtil.getParam(request, "id", "");
		String idString = RequestUtil.getParam(request, "idString", "");

		boolean isFlag = false;
		if (!"".equals(id))
			isFlag = service.deleteById(id);
		else
			isFlag = service.deleteByIdString(idString);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		if (isFlag)
			message = "删除成功";
		else
			message = "删除失败";
		StringBuffer sb = new StringBuffer("[");
		sb.append("{\"message\":\"" + message + "\"" + "}");
		sb.append("]");

		try {
			out = response.getWriter();
			out.println(sb.toString());
		} catch (IOException e) {

			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 置顶操作
	 * @return
	 */
	public String toTop() {
		String topType = RequestUtil.getParam(request, "topType", "");
		String idString = RequestUtil.getParam(request, "idString", "");
		
		boolean isFlag = false;
			isFlag = service.toTop(topType,idString);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		if (isFlag)
			message = "操作成功";
		else
			message = "操作失败";
		StringBuffer sb = new StringBuffer("[");
		sb.append("{\"message\":\"" + message + "\"" + "}");
		sb.append("]");
		
		try {
			out = response.getWriter();
			out.println(sb.toString());
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		return null;
	}
	
	public String modifyTribunePage(){
		String id = RequestUtil.getParam(request, "id", "0");
		triObj = service.getById(id);
		if(null==triObj){
			triObj = new Tribune();
			triObj.setId(Long.valueOf(0));
		}
		return "modifyTribunePage";
	}
	
	public List<Tribune> getTriList() {
		return triList;
	}

	public void setTriList(List<Tribune> triList) {
		this.triList = triList;
	}

	public Tribune getTriObj() {
		return triObj;
	}

	public void setTriObj(Tribune triObj) {
		this.triObj = triObj;
	}

	public List<TribuneFlow> getTriFlowList() {
		return triFlowList;
	}

	public void setTriFlowList(List<TribuneFlow> triFlowList) {
		this.triFlowList = triFlowList;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public List<Tribune> getRows() {
		return rows;
	}

	public void setRows(List<Tribune> rows) {
		this.rows = rows;
	}

    public TribunePresented getTrip() {
        return trip;
    }

    public void setTrip(TribunePresented trip) {
        this.trip = trip;
    }

    public TribuneFlow getTrif() {
        return trif;
    }

    public void setTrif(TribuneFlow trif) {
        this.trif = trif;
    }

	public TgAnnouncement getTgAnnouncement() {
		return tgAnnouncement;
	}

	public void setTgAnnouncement(TgAnnouncement tgAnnouncement) {
		this.tgAnnouncement = tgAnnouncement;
	}
	
	
}